<template>
  <!-- 安全职责与责任书下发 -->
  <div class="postrespo">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        ref="crud"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >

        <!-- 左上方操作栏 -->
        <template slot="menuLeft">
          <el-button
            type="success"
            size="small"
            icon="el-icon-finished"
            plain
            @click="handleBatchDistribute">
            批量下发责任书
          </el-button>
        </template>

        <!-- 附件表格自定义 -->
        <template slot="fj" slot-scope="scope">
          <div class="enclosure_div" v-if="scope.row['bladeFiles'] && scope.row['bladeFiles'].length !== 0">
            <a 
              v-for="(item, index) in scope.row['bladeFiles']" 
              :key="index"
              :href="downloadHead + item.id" >
              <p><i class="el-icon-download"></i>下载附件{{index + 1}}</p>
            </a>
          </div>
          <span v-else>-</span>
        </template>

        <!-- 状态表格自定义 -->
        <template slot="status" slot-scope="scope">
          <span>{{formatStatus(scope.row)}}</span>
        </template>

        <!-- 审批表格自定义 -->
        <template slot="approve" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['auditPermissions'] && scope.row['sfzf'] !== 1"
              type="success"
              size="mini"
              @click="handleExamine(scope.row)">
              审 核
            </el-button>
            <el-button
              v-if="scope.row['approvalPermissions'] && scope.row['sfzf'] !== 1"
              type="warning"
              size="mini"
              @click="handleApprove(scope.row)">
              批 准
            </el-button>
            <span v-if="scope.row['sfzf'] === 1 || ( !scope.row['auditPermissions'] && !scope.row['approvalPermissions'] )">-</span>
          </div>
        </template>

        <!-- 责任书表格自定义 -->
        <template slot="responseLetter" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['gxsj'] === undefined || scope.row['gxsj'] === '' || scope.row['gxsj'] === null"
              type="success"
              size="mini"
              icon="el-icon-plus"
              @click="handleAddResponseLetter(scope.row)">
              添加责任书
            </el-button>
            <el-button
              v-else
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEditResponseLetter(scope.row)">
              修订责任书
            </el-button>
          </div>
        </template>
        
        <!-- 下发表格自定义 -->
        <template slot="distribute" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['sfxf'] === 0 && scope.row['zt'] === 3"
              type="danger"
              size="mini"
              icon="el-icon-finished"
              @click="handleDistribute(scope.row)">
              下 发
            </el-button>
            <el-tag v-if="scope.row['sfxf'] === 1" type="success" size="small">已下发</el-tag>
            <span v-if="statusObj[scope.row['zt']] !== '批准通过' || (scope.row['sfxf'] !==0 && scope.row['sfxf'] !== 1)">-</span>
          </div>
        </template>

      </avue-crud>

      <!-- 弹窗：添加&修订责任书、审核&批准责任书 -->
      <el-dialog 
        :title="dialogTitle"
        append-to-body
        :visible.sync="updateDialog"
        :close-on-click-modal="false" 
        :before-close="closeUpdateDialog"
        width="60%"
        class="update_dialog"
      >

        <!-- 内容 -->
        <avue-form 
          ref="updateForm" 
          v-model="updateObj" 
          :option="updateOption" 
          @submit="confirmUpdate"
        >

          <!-- 附件表单自定义 -->
          <template slot="fj">
            <div>
              <el-upload
                v-if="updateDialogType === addStr || updateDialogType === editStr"
                action="/api/fileManager/upload/file"
                :headers="SetHeaders"
                :file-list="fjFileList"
                :before-upload="beforeUploadFJ"
                :on-remove="handleRemoveFJ"
                :on-success="uploadFJSuccess"
              >
                <el-button 
                  size="small" 
                  type="primary" 
                  icon="el-icon-document">
                  选择文件
                </el-button>
              </el-upload>

              <a
                v-else-if="updateDialogType !== addStr && updateDialogType !== editStr && fjFileList && fjFileList.length > 0"
                v-for="(item, index) in fjFileList"
                :key="index"
                :href="downloadHead + item.response.data.id"
                style="color:#409EFF"
              >
                <p style="margin-top: 0px; margin-bottom: 0px;">
                  <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
                </p>
              </a>

              <span v-else>-</span>
            </div>
          </template>

          <!-- 自定义按钮 -->
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeUpdateDialog()">
              取 消
            </el-button>
          </template>

        </avue-form>

      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  add,
  update,
  getStatusList,
  modifyStatus,
  issued
} from "@/api/duty/dutiesandresponsibilities/postrespo";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

export default {
  data() {
    return {
      // 列表
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menu: false,
        selectable:(row) => {
          if(row['sfxf'] === 0 && row['zt'] === 3) {
            return true;
          }
          return false;
        },
        column: [
          {
            label: "岗位名称",
            prop: "postId",
            width: 120,
            align: "center",
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/post/select?tenantId=" + tenantId,
            props: {
              label: "postName",
              value: "id",
            }
          },
          {
            label: "更新时间",
            prop: "gxsj",
            align: "center",
            width: 100
          },
          {
            label: "编制人",
            prop: "bzren",
            align: "center",
            width: 100,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            }
          },
          {
            label: "审核人",
            prop: "shren",
            width: 100,
            align: "center",
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            }
          },
          {
            label: "批准人",
            prop: "pzren",
            width: 100,
            align: "center",
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            }
          },
          {
            label: "备注",
            prop: "bz",
            align: "center"
          },
          {
            label: "附件",
            prop: "fj",
            align: "center",
            width: 100,
            slot: true
          },
          {
            label: "状态",
            prop: "status",
            align: "center",
            width: 100,
            slot: true
          },
          {
            label: "审批",
            prop: "approve",
            align: "center",
            width: 100,
            slot: true
          },
          {
            label: "责任书",
            prop: "responseLetter",
            align: "center",
            width: 150,
            slot: true
          },
          {
            label: "下发",
            prop: "distribute",
            align: "center",
            width: 100,
            slot: true
          }
        ]
      },
      statusObj: {},
      // 弹窗：添加&修订责任书、审核&批准责任书
      updateDialogType: "",
      examineStr: "EXAMINE",
      approveStr: "APPROVE",
      addStr: "ADD",
      editStr: "EDIT",
      dialogTitle: "",
      updateDialog: false,
      updateObj: {},
      // 附件
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      fjFileList: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.postrespo_add, false),
        viewBtn: this.vaildData(this.permission.postrespo_view, false),
        delBtn: this.vaildData(this.permission.postrespo_delete, false),
        editBtn: this.vaildData(this.permission.postrespo_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },

    updateOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "岗位名称",
            prop: "postId",
            disabled: true,
            type: "select",
            dicUrl: "/api/blade-system/post/select?tenantId=" + tenantId,
            props: {
              label: "postName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择岗位名称",
              trigger: "change"
            }]
          },
          {
            label: "编制人",
            prop: "bzren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择编制人",
              trigger: "change"
            }]
          },
          {
            label: "岗位职责",
            prop: "gwaqzz",
            disabled: true,
            span: 24,
            type: "textarea",
            maxLength: 250,
            rules: [{
              required: true,
              message: "请输入岗位安全职责",
              trigger: "blur"
            }]
          },
          {
            label: "审核人",
            prop: "shren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择审核人",
              trigger: "change"
            }]
          },
          {
            label: "批准人",
            prop: "pzren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择批准人",
              trigger: "change"
            }]
          },
          {
            label: "考核人",
            prop: "khren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择考核人",
              trigger: "change"
            }]
          },
          {
            label: "附件",
            prop: "fj",
            disabled: true,
            slot: true,
            formslot: true
          },
          {
            label: "备注",
            prop: "bz",
            disabled: true,
            span: 24,
            type: "textarea",
            maxLength: 250
          },
          {
            label: "部门审核",
            prop: "deptExamine",
            disabled: true,
            display: false,
            type: "radio",
            dicData: [{
              label: "同意",
              value: 1
            }, {
              label: "不同意",
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择部门审核意见",
              trigger: "change"
            }]
          },
          {
            label: "领导批准",
            prop: "leaderApprove",
            disabled: true,
            display: false,
            type: "radio",
            dicData: [{
              label: "同意",
              value: 1
            }, {
              label: "不同意",
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择领导批准意见",
              trigger: "change"
            }]
          }
        ]
      } 
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化页面
    initData() {
      getStatusList().then(res => {
        this.statusObj = {};
        res.data.data.forEach(item => {
          this.statusObj[item.dictKey] = item.dictValue;
        });
      }).then(() => {
        this.onLoad(this.page);
      });
    },

    // 格式化状态列
    formatStatus(row) {
      var zt = row.zt;
      if(this.statusObj[zt] === undefined) {
        return "-";
      } else {
        return this.statusObj[zt];
      }
    },

    // 下发一条责任书
    handleDistribute(row) {
      this.$confirm("确定下发选择责任书?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return issued(row.id);
      }).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "下发成功!"
        });
      });
    },

    // 下发多条责任书
    handleBatchDistribute() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条责任书");
        return;
      }
      this.$confirm("确定下发选择责任书?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return issued(this.ids);
      }).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.$refs.crud.toggleSelection();
      });
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传附件
     */

    // 上传附件前
    beforeUploadFJ(file) {
      console.log(file);
      var isLimit = this.fjFileList.length + 1 <= 2;
      if (!isLimit) {
        this.$message.warning("最多选择两个附件!");
      }
      return isLimit;
    },

    // 上传附件成功
    uploadFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.fjFileList = fileList;
      this.updateObj.fj = this.formatFormFJ(this.fjFileList);
    },

    // 删除附件
    handleRemoveFJ(file, fileList) {
      this.fjFileList = fileList;
      this.updateObj.fj = this.formatFormFJ(this.fjFileList);
    },

    // 获取添加&修订责任书弹窗附件ID
    formatFormFJ(fileList) {
      var fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.response.data.id);
      });
      return fileIds.join(",");
    },

    /**
     * 弹窗：添加&修订责任书、审核&批准责任书
    */

    // 获取弹窗数据
    formatUpdateObj(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      return data;
    },

    // 获取部门审核、领导批准字段值
    formatExamineApproveValue(obj) {
      if(obj.zt === 0) {
        obj["deptExamine"] = "";
        obj["leaderApprove"] = "";
      } else if(obj.zt === 1) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 2) {
        obj["deptExamine"] = 2;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 3) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 1;
      } else if(obj.zt === 4) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 2;
      }
    },

    // 打开审核弹窗
    handleExamine(row) {
      this.updateDialogType = this.examineStr;
      this.dialogTitle = "审核责任书";
      this.updateObj = this.formatUpdateObj(row);
      this.fjFileList = [];
      this.updateDialog = true;
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "[]") {
        row.bladeFiles.forEach(item => {
          this.fjFileList.push({
            name: item.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: item
            }
          });
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop !== "deptExamine" && item.prop !== "leaderApprove") {
          item.disabled = true;
        }
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = false;
        }
        if(item.prop === "leaderApprove") {
          item.display = false;
          item.disabled = true;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 打开批准弹窗
    handleApprove(row) {
      this.updateDialogType = this.approveStr;
      this.dialogTitle = "批准责任书";
      this.updateObj = this.formatUpdateObj(row);
      this.fjFileList = [];
      this.updateDialog = true;
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "[]") {
        row.bladeFiles.forEach(item => {
          this.fjFileList.push({
            name: item.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: item
            }
          });
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop !== "deptExamine" && item.prop !== "leaderApprove") {
          item.disabled = true;
        }
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = true;
        }
        if(item.prop === "leaderApprove") {
          item.display = true;
          item.disabled = false;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 打开添加责任书弹窗
    handleAddResponseLetter(row) {
      this.updateDialogType = this.addStr;
      this.dialogTitle = "添加责任书";
      this.updateObj = this.formatUpdateObj(row);
      this.fjFileList = [];
      this.updateDialog = true;
      this.updateOption.column.forEach(item => {
        if(item.prop === "deptExamine" || item.prop === "leaderApprove") {
          item.display = false;
          item.disabled = true;
        }else if(item.prop !== "postId") {
          item.disabled = false;
        }
      });
    },

    // 打开修订责任书弹窗
    handleEditResponseLetter(row) {
      this.updateDialogType = this.editStr;
      this.dialogTitle = "修订责任书";
      this.updateObj = this.formatUpdateObj(row);
      this.fjFileList = [];
      this.updateDialog = true;
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "[]") {
        row.bladeFiles.forEach(item => {
          this.fjFileList.push({
            name: item.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: item
            }
          });
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop === "deptExamine" || item.prop === "leaderApprove") {
          item.display = false;
          item.disabled = true;
        }else if(item.prop !== "postId") {
          item.disabled = false;
        }
      });
    },

    // 点击确定按钮
    confirmUpdate() {
      if(this.updateDialogType === this.examineStr) {
        this.confirmExamine();
      } else if(this.updateDialogType === this.approveStr) {
        this.confirmApprove();
      } else if(this.updateDialogType === this.addStr) {
        this.confirmAdd();
      } else if(this.updateDialogType === this.editStr) {
        this.confirmEdit();
      }
    },

    // 确定审核
    confirmExamine() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.deptExamine).then(res => {
            if(res.data.success) {
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 确定批准
    confirmApprove() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.leaderApprove).then(res => {
            if(res.data.success) {
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 确定添加责任书
    confirmAdd() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          var addRow = this.formatUpdateObj(this.updateObj);
          add(addRow).then(res => {
            if(res.data.success) {
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 确定修订责任书
    confirmEdit() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          var updateRow = this.formatUpdateObj(this.updateObj);
          update(updateRow).then(res => {
            if(res.data.success) {
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 取消、关闭添加&修订责任书、审核&批准责任书弹窗
    closeUpdateDialog() {
      this.updateDialogType = "";
      this.dialogTitle = "";
      this.updateObj = {};
      this.fjFileList = [];
      this.updateDialog = false;
    }

  }
};
</script>

<style lang="scss" scpoed>
.postrespo {
  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      p {
        margin-top: 0px;
        margin-bottom: 0px;
      }

      i {
        margin-right: 5px;
      }
    }
  }
}

.update_dialog {
  .avue-form__menu--center {
    text-align: center;
  }
}
</style>